#include "welcomepage.h"
#include "ui_welcomepage.h"
#include "qpalette.h"
#include "QPainter"
#include <mutex>
#include <Windows.h>
#include "Config/constant.h"
#include "others/wmic.h"
#include "QRCode/qrencode.h"
#include "dialog/myhelper.h"

WelcomePage::WelcomePage(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::WelcomePage)
{
    ui->setupUi(this);
    if(Constant::ShowFullScreen)
        this->showFullScreen();
//    setBg();
    ui->tabWidget_state->setCurrentIndex(0);


    QCoreApplication::setOrganizationName(QString("QXZD"));
    QCoreApplication::setApplicationName(QString("Qt"));
    QSettings settings(QSettings::NativeFormat, QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
    WMIC wmic;
    QString id=wmic.getCpuId();

//    ui->soft_regist_lineEdit->setText(id);
    qDebug()<<"id"<<id;
    qDebug()<<"settings="<<settings.value("Name").toString();
    QString id_r=wmic.MachineCodetoIDNumber(settings.value("Name").toString());
    QString mc=wmic.IDNumbertoMachineCode(id);
    timer.setInterval(1000);
    connect(&timer,SIGNAL(timeout()),this,SLOT(CheckSystemFile()));

    if(id==id_r){
        //注册成功，隐藏注册页面
        showBtn_enter=true;
        ui->tabWidget_state->setCurrentIndex(2);
        timer.start();
    }else{
        ui->tabWidget_state->setCurrentIndex(1);
        showBtn_enter=false;
        ui->label_2->setPixmap(createQRCode(id));
    }

    flag=0;
    error=0;
    m_freeSpace=5;//设定小于5G提醒用户删除数据

    fsp=new FuncSelectPage();
    fsp->hide();





}

WelcomePage::~WelcomePage()
{
    delete fsp;
    delete ui;
}
bool WelcomePage::isFressSpaceEnough()
{
    QString path = "D:/";//设置被监控磁盘
    QFileInfo fileInfo(path);
    QString strDiskName = fileInfo.absolutePath();

    qint64 nFreeSpace = getDiskFreeSpace(strDiskName);

    bool bEnough = false;
    if( nFreeSpace > m_freeSpace )
    {
        bEnough = true;
    }
    else
    {
        bEnough = false;
    }
    return bEnough;
}

quint64 WelcomePage::getDiskFreeSpace(QString iDriver)
{
    LPCWSTR strDriver = (LPCWSTR)iDriver.utf16();
    ULARGE_INTEGER freeDiskSpaceAvailable, totalDiskSpace, totalFreeDiskSpace;

    //调用函数获取磁盘参数(单位为字节Byte),转化为GB，需要除以(1024*1024*1024)
    GetDiskFreeSpaceExW( strDriver, &freeDiskSpaceAvailable, &totalDiskSpace, &totalFreeDiskSpace) ;

    qDebug() << "total space is:" << (quint64)totalDiskSpace.QuadPart/(1024*1024*1024);
    qDebug() << "free  space is:" << (quint64)totalFreeDiskSpace.QuadPart/(1024*1024*1024);

    return (quint64)totalFreeDiskSpace.QuadPart/GB;
}


void WelcomePage::CheckSystemFile()
{
    flag++;
    if(flag==1)
        ui->label_info->setText("正在检查系统文件，请稍后...");
    else if(flag==2)
    {
        ui->label_info->setText("系统文件存在，正在检查硬盘大小...");
    }else if(flag==3)
    {
        if(isFressSpaceEnough())
        {
            ui->label_info->setText("磁盘空间大于5G,足够使用。");
        }else
        {
            ui->label_info->setText("磁盘空间小于5G,请您联系技术支持进行处理。");
        }

    }else if(flag==4)
    {
        bool findCom=false;
        foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
        {
            qDebug()<<info.portName();
            qDebug()<<info.vendorIdentifier();
            qDebug()<<info.productIdentifier();
            if(info.vendorIdentifier()==0x0403 && info.productIdentifier()==0x6001)
            {
                findCom=true;
            }

        }
        if(findCom)
        {
            ui->label_info->setText("设备存在...");
        }else
        {
            ui->label_info->setText("设备不存在...请确认设备驱动已安装并且已经插入设备usb接口！");
            error=1;
        }
    }else
    {
        disconnect(&timer,SIGNAL(timeout()),this,SLOT(CheckSystemFile()));
        timer.stop();


        bool uc=true;
        if(Constant::UseControl)
        {
            QDateTime Time = QDateTime::currentDateTime();
            QString t_year=Time.toString("yyyy");//格式化时间
            QString t_month=Time.toString("MM");//格式化时间
            if(t_month.toInt()<=12 && t_year.toInt()<=2023)
            {
                uc=true;
            }else
            {
                uc=false;
            }
        }else
        {
            uc=true;
        }

        if(showBtn_enter && error==0 && uc){
            ui->tabWidget_state->setCurrentIndex(3);
        }else{
            ui->tabWidget_state->setCurrentIndex(2);
        }

    }

}
/**
 * 功能：设置背景图片
 * @brief WelcomePage::setBg
 */
void WelcomePage::setBg()
{
    this->setAutoFillBackground(true);
    QPalette pal = this->palette();
    QPixmap bgImage(":/images/welcomePage/bg_welcome.png");
    qDebug()<<this->size();
    pal.setBrush(QPalette::Window,QBrush(bgImage.scaled(this->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation)));
    setPalette(pal);
}

void WelcomePage::on_pb_exit_clicked()
{
    this->close();
}


void WelcomePage::on_pb_enter_clicked()
{
    fsp->show();

    ui->tabWidget_state->setCurrentIndex(0);
    this->close();
}
void WelcomePage::paintEvent(QPaintEvent *event)
{
    //通过这种方式可以将图片平铺到窗口上
    //使用样式表可以很方便设置界面，而且非常高效，还能让界面和逻辑分离
    //不过在本例中由于是顶层窗口，所以直接设置样式表也不会显示。
    //所以样式表比较适合子窗口来使用。
    QPainter painter(this);
    painter.drawPixmap(rect(),QPixmap(":/images/welcomePage/bg_welcome.png"),QRect());
}

void WelcomePage::on_pushButton_regist_clicked()
{
    QCoreApplication::setOrganizationName(QString("QXZD"));
    QCoreApplication::setApplicationName(QString("Qt"));
    QSettings settings(QSettings::NativeFormat, QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
    QString MachineCode=ui->soft_regist_lineEdit->text();
    WMIC wmic;
    QString res=wmic.getCpuId();
    QString ID=wmic.MachineCodetoIDNumber(MachineCode);

    if(ID==res){
        myHelper::ShowMessageBoxInfo("恭喜您，注册成功！");
        settings.setValue("Name", MachineCode);
        ui->tabWidget_state->setCurrentIndex(2);
        showBtn_enter=true;
        timer.start();
    }else{
        myHelper::ShowMessageBoxError("注册失败，请联系技术支持！");
    }
}

QPixmap WelcomePage::createQRCode(const QString &text)
{
    int margin = 2;
    if (text.length() == 0)
    {
        return QPixmap();
    }
    QRcode *qrcode = QRcode_encodeString(text.toLocal8Bit(), 2, QR_ECLEVEL_L, QR_MODE_8, 0);
    if (qrcode == NULL) {
        return QPixmap();
    }
    unsigned char *p, *q;
    p = NULL;
    q = NULL;
    int x, y, bit;
    int realwidth;

    realwidth = qrcode->width;
    QImage image = QImage(realwidth, realwidth, QImage::Format_Indexed8);
    QRgb value;
    value = qRgb(255,255,255);
    image.setColor(0, value);
    value = qRgb(0,0,0);
    image.setColor(1, value);
    image.setColor(2, value);
    image.fill(0);
    p = qrcode->data;
    for(y=0; y<qrcode->width; y++) {
        bit = 7;
        q += margin / 8;
        bit = 7 - (margin % 8);
        for(x=0; x<qrcode->width; x++) {
            if ((*p & 1) << bit)
                image.setPixel(x, y, 1);
            else
                image.setPixel(x, y, 0);
            bit--;
            if(bit < 0)
            {
                q++;
                bit = 7;
            }
            p++;
        }
    }
    return QPixmap::fromImage(image.scaledToWidth(120));
}
